from typing import Any

from aiogram import F, types
from aiogram_dialog import Dialog, DialogManager, Window
from aiogram_dialog.widgets.kbd import Button
from aiogram_dialog.widgets.text import Const
from sqlalchemy.ext.asyncio import AsyncSession

from app.bot.states.user import SoftState
from app.bot.utils.logger import logger
from app.database.requests import change_soft_status, get_soft_status


async def soft_on(call: types.CallbackQuery, widget: Any, manager: DialogManager):
    session = manager.middleware_data.get("session")
    user_id = call.from_user.id
    try:
        await change_soft_status(session, user_id, 1)
        await call.answer("🟢 Софт запущен")
    except Exception as e:
        logger.exception(e)
        await call.answer("Произошла ошибка")


async def soft_off(call: types.CallbackQuery, widget: Any, manager: DialogManager):
    session = manager.middleware_data.get("session")
    user_id = call.from_user.id
    try:
        await change_soft_status(session, user_id, 0)
        await call.answer("🔴 Софт выключен")
    except Exception as e:
        logger.exception(e)
        await call.answer("Произошла ошибка")


async def get_soft_status_data(
    session: AsyncSession, dialog_manager: DialogManager, **kwargs
):
    user_id = dialog_manager.event.from_user.id
    soft_status = await get_soft_status(session, user_id)

    return {"soft_on": soft_status}


soft_dialog = Dialog(
    Window(
        Const("Софт отключен", when=~F["soft_on"]),
        Const("Софт работает", when=F["soft_on"]),
        Button(
            Const("🟢 Запустить софт"),
            id="soft_on",
            on_click=soft_on,
            when=~F["soft_on"],
        ),
        Button(
            Const("🔴 Выключить софт"),
            id="soft_off",
            on_click=soft_off,
            when=F["soft_on"],
        ),
        state=SoftState.display_soft_status,
        getter=get_soft_status_data,
    )
)
